<?php

/**
 * Author renshan
 * Created At 2016-08-27 13:00:00
 *
 * 路由处理类
 */
namespace Mkd\Route;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route as BaseRoute;
use Mkd\Request\Request;

class Route
{
	public static  function matchRoute()
	{

		$request = Request::request();

		$config = Yaml::parse(file_get_contents(ROOT.'/app/config/routing.yml'));

		$routes = new RouteCollection();

		foreach ($config as $key => $route) {
			$path = $route['route'];
			$map = $route['map'];
			$methods = isset($route['methods']) ? $route['methods'] : [];
			$requirements = isset($route['requirements']) ? $route['requirements'] : [];

			if (!is_array($methods)) {
				throw new Exception("methods in route {$_route} must an array");
			}
			
			if (!is_array($requirements)) {
				throw new Exception("requirements in route {$_route} must an array");
			}

			$route = new BaseRoute($path);

			$mapArr = explode(":", $map);
			$controller = "{$mapArr[0]}\\Controller\\{$mapArr[1]}Controller";
			$action = "${mapArr[2]}Action";

			$route->setDefaults(['controller' => $controller, 'action' => $action]);
			$route->setRequirements($requirements);
			$route->setmethods($methods);

			$routes->add($key, $route);
		}

		$context = new RequestContext();
		$context->fromRequest($request);
		$matcher = new UrlMatcher($routes, $context);

		return $matcher->match($request->getPathInfo());
	}

}

?>
